package com.lingjtx.common.captcha;

import com.lingjtx.common.core.RedisOptions;
import com.lingjtx.common.core.util.CommonUtil;
import com.lingjtx.common.core.util.StringUtil;

import java.util.Objects;

public class CaptchaGenerator {

    public static CaptchaVo generator(CaptchaType type, RedisOptions redis) {
        CaptchaHandle handle = CaptchaType.getObject(type);
        if (Objects.nonNull(handle)) {
            return handle.generator(redis);
        }
        return null;
    }

    // 第一次校验位置信息,校验成功返回第二次验证令牌
    public static String valid(CaptchaType type, String captchaUid, String pointJson, RedisOptions redis) {
        CaptchaHandle handle = CaptchaType.getObject(type);
        if (Objects.nonNull(handle)) {
            return handle.valid(captchaUid, pointJson, redis);
        }
        return null;
    }

    // 第二次验证令牌
    public static boolean verify(String captchaUid, String authenticate, RedisOptions redis) {
        String secondKey = String.format(CaptchaHandle.REDIS_SECOND_CAPTCHA_KEY, authenticate);
        String uid = (String) redis.get(secondKey);
        if (StringUtil.isNotEmpty(uid) && uid.equals(captchaUid)) {
            redis.delete(secondKey);
            return true;
        }
        return false;
    }
}
